package com.gitee.qdbp.jdbc.tags;

import java.io.IOException;
import com.gitee.qdbp.able.enums.WrapMode;
import com.gitee.qdbp.jdbc.api.SqlBoot;
import com.gitee.qdbp.jdbc.sql.SqlBuffer;
import com.gitee.qdbp.jdbc.sql.SqlTools;
import com.gitee.qdbp.staticize.common.IWriter;
import com.gitee.qdbp.staticize.exception.TagException;
import com.gitee.qdbp.staticize.tags.base.NextStep;

/**
 * 去掉第1个prefixOverrides, 去掉最后一个suffixOverrides<br>
 * 在前面增加prefix, 在后面增加suffix<br>
 *
 * @author zhaohuihua
 * @version 20200906
 * @since 3.2.0
 */
public abstract class TrimBase extends SqlCachingTag {

    public TrimBase(SqlBoot sqlBoot) {
        super(sqlBoot);
    }

    private String prefix;
    private String suffix;
    private String prefixOverrides;
    private String suffixOverrides;
    /** 是否添加括号 **/
    private WrapMode brackets;

    protected String getPrefix() {
        return prefix;
    }

    protected void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    protected String getSuffix() {
        return suffix;
    }

    protected void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    protected String getPrefixOverrides() {
        return prefixOverrides;
    }

    protected void setPrefixOverrides(String prefixOverrides) {
        this.prefixOverrides = prefixOverrides;
    }

    protected String getSuffixOverrides() {
        return suffixOverrides;
    }

    protected void setSuffixOverrides(String suffixOverrides) {
        this.suffixOverrides = suffixOverrides;
    }

    protected WrapMode getBrackets() {
        return brackets;
    }

    protected void setBrackets(String brackets) {
        this.brackets = WrapMode.of(brackets, "brackets value");
    }

    @Override
    public NextStep doHandle() {
        return NextStep.EVAL_BODY;
    }

    @Override
    protected void doEnded(SqlBuffer buffer, IWriter writer) throws TagException, IOException {
        if (buffer.isBlank()) {
            return;
        }

        SqlTools.wrap(buffer, brackets, prefix, prefixOverrides, suffix, suffixOverrides);
        String leadingBlank = clearLeadingBlank();
        if (leadingBlank != null) {
            buffer.shortcut().pd(leadingBlank);
        }

        writer.write(buffer);
    }
}
